package com.learn.security.modules.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.security.modules.vo.R;
import com.learn.security.modules.security.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * created by yuanjunjie on 2019/6/10 3:49 PM
 */
@Slf4j
@Component("jcAuthenticationFailureHandler")
public class JCAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    public JCAuthenticationFailureHandler() {
        this.setDefaultFailureUrl(SecurityConstants.LOGIN_URL_PAGE+"?error=true");
    }
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException exception) throws IOException, ServletException {
        if (httpServletRequest.getRequestURI().contains(SecurityConstants.WEIXIN_REDIRECT_PROCESSING_URL)) {
            log.info("微信登录失败:{}", exception);
            super.onAuthenticationFailure(httpServletRequest, httpServletResponse, exception);
        } else {
            log.info("手机号登录失败");
            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(R.error(exception.getMessage())));
        }
    }


}
